﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using BartonExtension;
using ProtoBuf;

namespace WSServer
{
    [ProtoContract]
    public class WSAccessToken : IDisposable
    {
        const int MAX_EXPIRED_TIMESPAN = 7200; 
        private bool disposed = false;
        private Timer timer;
        private Action<WSAccessToken> onTokenExpired;

        [ProtoMember(1)]
        public string access_token { get; set; }
        [ProtoMember(2)]
        public DateTime createTime { get; set; }

        public void Dispose()
        {
            if (!disposed)
            {
                Dispose(true);
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }
            if (disposing)
            {
                // 清理托管资源
                if (timer != null)
                {
                    timer.Change(Timeout.Infinite, 0);
                    timer.Dispose();
                    timer = null;
                }
            }
            disposed = true;
        }
        public int expired_in
        {
            get
            {
                return Math.Max(0, (DateTime.Now - createTime).TotalSeconds).toInt32().Value;
            }
        }
        private bool isExpired
        {
            get
            {
                return expired_in == 0;
            }
        }

        private void Refresh()
        {
            access_token = IDGenerator.GenerateID().ToString();
            createTime = DateTime.Now;
        }
        public WSAccessToken(Action<WSAccessToken> onTokenExpired)
        {
            this.onTokenExpired = onTokenExpired;
            timer = new Timer((o) =>
            {
                if(this.isExpired)
                {
                    Refresh();
                    this.onTokenExpired(this);
                }
            }, null, 3 * 60 * 1000, 3 * 60 * 1000);
        }
        public bool isValid(string _token)
        {
            return access_token == _token;
        }
    }
}
